package com.ruoyi.web.controller.tool;

import java.io.File;
import java.net.URL;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.apache.commons.io.FileUtils;

import com.alibaba.fastjson.JSONObject;

public class JsInvoke {

	static ScriptEngineManager m = new ScriptEngineManager();
	// 获取JavaScript执行引擎
	static ScriptEngine engine = m.getEngineByName("JavaScript");

	public static Object invokeFun(JSONObject obj,String fun) {
		try {
			ClassLoader classLoader = JsInvoke.class.getClassLoader();
			URL url = classLoader.getResource("users.js");
			//获取当前类所在的目录，即jar包目录
			String property = System.getProperty("user.dir");
			//获取自定义配置文件的路径
			String configLocation = property + "/config/users.js";
			File file = null;
			try{
				file = new File(configLocation);
			}catch (Exception e){
				e.printStackTrace();
				file = new File(url.getFile());
			}
			String js = FileUtils.readFileToString(file, "utf-8");
			engine.eval(js);
			if (engine instanceof Invocable) {
				Invocable invoke = (Invocable) engine;
				Object c = invoke.invokeFunction(fun, obj);
				return c;
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
